package com.by.yz.loginUtil;

import android.content.Context;
import android.util.Log;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.by.yz.App;
import com.by.yz.activity.regitser.RegisterInfoActivity;
import com.by.yz.loginUtil.Constants;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.net.CookieStore;
import java.net.HttpCookie;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by wlx on 6/14/16.
 */
public class FeedBackRESTFul {

    public interface MyGetCallBack{
        public void ok(JSONArray response) throws JSONException;
        public void error(String error);
    }
    public interface  MyPostCallBack{
        public void ok(JSONObject response) throws JSONException;
        public void error(String error);

    }

    public void postFeedback(JSONObject data,final MyPostCallBack cb){

        String url = Constants.server_url + "/api/feedbacks";

        JsonObjectRequest postRequest = new JsonObjectRequest(Request.Method.POST, url, data,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        try {
                            Log.e("FBR-success","1");
                            cb.ok(response);
                            cb.ok(response);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e("FBR-error","0");
                cb.error(error.toString());
            }
        }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                HashMap<String, String> headers = new HashMap<String, String>();
                CookieStore cookieJar = App.cookieManager.getCookieStore();
                List<HttpCookie> cookies = cookieJar.getCookies();
                for (HttpCookie cookie : cookies) {
                    if (cookie.toString().contains("XSRF-TOKEN")) {
                        Log.e("token-post", cookie.getValue());
                        headers.put("X-XSRF-TOKEN", cookie.getValue());
                    }
                }

                headers.put("Content-Type", "application/json; charset=utf-8");
                return headers;
            }
        };
        App.requestQueue.add(postRequest);
    }
}
